#include "my_inc/main_login.h"

// 存储UI元素的全局变量
static lv_obj_t * g_cont_game     = NULL;
static lv_obj_t * g_score_label   = NULL;
static lv_obj_t * highscore_label = NULL;
static size_t top                 = 0;
static int g_current_score        = 0;
// 全局变量
// static lv_timer_t * g_game_timer = NULL;
static game_state_t g_game_state = GAME_RUNNING;
static lv_timer_t * game_timer_2048;

/**
 * @brief 根据数字值获取对应的背景颜色
 * @param value 方块数字值
 * @return 对应的颜色值
 */
uint32_t get_tile_color(int value)
{
    switch(value) {
        case 0: return 0xcdc1b4; // 空白方块背景
        case 2: return 0xeee4da;
        case 4: return 0xede0c8;
        case 8: return 0xf2b179;
        case 16: return 0xf59563;
        case 32: return 0xf67c5f;
        case 64: return 0xf65e3b;
        case 128: return 0xedcf72;
        case 256: return 0xedcc61;
        case 512: return 0xedc850;
        case 1024: return 0xedc53f;
        case 2048: return 0xedc22e;
        case 4096: return 0xec3c2d;
        case 8192: return 0xec3c2d;
        default: return 0xff0000; // 超过8192的数值
    }
}

/**
 * @brief 更新分数显示
 */
void update_score_display(int score)
{
    if(g_score_label) {
        char score_text[20];
        snprintf(score_text, sizeof(score_text), "分数: %d", score);
        lv_label_set_text(g_score_label, score_text);
    }
}

/**
 * @brief 游戏更新定时器回调
 */
void update_game_board(lv_timer_t * timer)
{
    lv_obj_t * game_over_label = (lv_obj_t *)timer->user_data;
    if(!g_cont_game || g_game_state != GAME_RUNNING) return;

    // 保存当前状态到temp
    for(int i = 0; i < FOUR; i++) {
        for(int j = 0; j < FOUR; j++) {
            temp[i][j] = data[i][j];
        }
    }

    // 获取用户输入并更新游戏状态
    int key   = get_arrow_key();
    int moved = 0;

    if(key != SLIDE_NONE) {
        switch(key) {
            case UP: moved = up(data, temp); break;
            case DOWN: moved = down(data, temp); break;
            case LEFT: moved = left(data, temp); break;
            case RIGHT: moved = right(data, temp); break;
        }

        if(moved == 1) {
            g_current_score += 2;
            update_score_display(g_current_score);
            refresh_game_ui(g_cont_game, data);
        }
    }

    // 检查游戏结束条件
    if(!get_config()) {
        // ⭐️ 关键：先刷新最后一次的棋盘状态
        refresh_game_ui(g_cont_game, data);
        lv_obj_clear_flag(game_over_label, LV_OBJ_FLAG_HIDDEN);
        // 然后处理游戏结束逻辑
        if(highscore_label) {
            size_t top_score = g_current_score > top ? g_current_score : top;
            char hi_text[20];
            snprintf(hi_text, sizeof(hi_text), "最高分: %d", top_score);
            lv_label_set_text(highscore_label, hi_text);
        }
        printf("游戏结束！最终分数: %d\n", g_current_score);
    }
}

// 2048游戏界面
void game_2048(face_p head)
{
    menu_p m_p          = malloc(sizeof(menu_t));
    m_p->btn_state      = 0;
    face_p temp         = faceinsertend(head, "2048");
    lv_obj_t * obj_main = lv_obj_create(temp->screen);
    lv_obj_set_size(obj_main, 800, 480);
    lv_obj_set_style_bg_color(obj_main, lv_color_hex(0xc1c1c1), LV_PART_MAIN);

    // 定义cont的2列网格（左400px + 右400px）、3行网格（上205px + 中205px + 下60px）
    static lv_coord_t col_dsc[] = {400, 400, LV_GRID_TEMPLATE_LAST};     // 明确2列，每列400px
    static lv_coord_t row_dsc[] = {205, 205, 60, LV_GRID_TEMPLATE_LAST}; // 3行，对应标题区、分数区、按钮区
    lv_obj_t * cont             = lv_obj_create(temp->screen);
    lv_obj_clear_flag(cont, LV_OBJ_FLAG_SCROLLABLE); // ⭐️ 关键代码：禁用滚动
    lv_obj_set_style_bg_color(cont, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
    lv_obj_set_style_bg_opa(cont, LV_OPA_0, LV_PART_MAIN); // 只设置背景的透明度
    lv_obj_set_style_grid_column_dsc_array(cont, col_dsc, 0);
    lv_obj_set_style_grid_row_dsc_array(cont, row_dsc, 0);
    lv_obj_set_size(cont, 800, 480);
    lv_obj_align(cont, LV_ALIGN_TOP_MID, 0, 0);
    lv_obj_set_style_pad_row(cont, 0, LV_PART_MAIN);
    lv_obj_set_style_pad_all(cont, 0, LV_PART_MAIN); // 去除内边距
    lv_obj_set_layout(cont, LV_LAYOUT_GRID);         // cont是2列3行的网格容器

    // -------------------------- 1. 左侧：游戏方块区域（cont_game） --------------------------
    // 4x4方块容器，放在cont的【第0列】（左侧400px），横跨3行（填满左侧高度）
    static lv_coord_t col_dsc_game[] = {100, 100, 100, 100, LV_GRID_TEMPLATE_LAST}; // 4列×100=400
    static lv_coord_t row_dsc_game[] = {120, 120, 120, 120, LV_GRID_TEMPLATE_LAST}; // 4行×120=480
    lv_obj_t * cont_game             = lv_obj_create(cont);
    g_cont_game                      = cont_game; // 保存全局引用
    lv_obj_clear_flag(cont_game, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_set_size(cont_game, 400, 480); // 大小匹配左侧列（400x480）
    lv_obj_add_event_cb(cont_game, event_handler, LV_EVENT_GESTURE, NULL);
    // 去除方块间隙，填满cont_game
    lv_obj_set_style_pad_all(cont_game, 0, LV_PART_MAIN);
    lv_obj_set_style_pad_column(cont_game, 0, LV_PART_MAIN);
    lv_obj_set_style_pad_row(cont_game, 0, LV_PART_MAIN);
    lv_obj_set_style_bg_color(cont_game, lv_color_hex(0xc1af9e), LV_PART_MAIN);
    // lv_style_set_radius(cont_game, LV_PART_MAIN);
    lv_obj_set_style_grid_column_dsc_array(cont_game, col_dsc_game, 0);
    lv_obj_set_style_grid_row_dsc_array(cont_game, row_dsc_game, 0);
    lv_obj_set_layout(cont_game, LV_LAYOUT_GRID);
    // 关键：将cont_game放在cont的【第0列】（左侧），横跨3行（填满高度）
    lv_obj_set_grid_cell(cont_game, LV_GRID_ALIGN_STRETCH, 0, 1, // 列：第0列（左），占1列
                         LV_GRID_ALIGN_STRETCH, 0, 3);           // 行：第0行开始，占3行（覆盖上/中/下）

    for(int i = 0; i < FOUR; i++) {
        for(int j = 0; j < FOUR; j++) {
            data[i][j] = 0;
        }
    }
    write_2048(data);
    write_2048(data);

    // 添加4x4游戏方块
    for(size_t i = 0; i < 4; i++) {
        for(size_t j = 0; j < 4; j++) {
            lv_obj_t * tile = lv_obj_create(cont_game);
            // 根据数字值设置不同的背景色
            uint32_t bg_color = get_tile_color(data[i][j]);
            lv_obj_set_style_bg_color(tile, lv_color_hex(bg_color), LV_PART_MAIN);
            lv_obj_set_style_border_width(tile, 2, LV_PART_MAIN);
            lv_obj_set_style_border_color(tile, lv_color_hex(0x776e65), LV_PART_MAIN);
            lv_obj_set_style_radius(tile, 4, LV_PART_MAIN);

            lv_obj_t * tile_label = lv_label_create(tile);
            // 将整数转换为字符串
            char num_str[10];
            if(data[i][j] == 0) {
                // 不完全隐藏，只是设置为透明
                lv_obj_set_style_bg_opa(tile, LV_OPA_0, LV_PART_MAIN);
                lv_obj_set_style_border_opa(tile, LV_OPA_50, LV_PART_MAIN); // 保留边框可见
                lv_label_set_text(tile_label, "");
            } else {
                snprintf(num_str, sizeof(num_str), "%d", data[i][j]);
                lv_label_set_text(tile_label, num_str);
            }
            lv_obj_set_style_text_font(tile_label, &lv_font_montserrat_24, 0); // 统一字体（避免之前的字体错误）
            lv_obj_center(tile_label);

            lv_obj_set_grid_cell(tile, LV_GRID_ALIGN_STRETCH, j, 1, LV_GRID_ALIGN_STRETCH, i, 1);
        }
    }

    // -------------------------- 2. 右侧：标签区域（标题、分数、最高分） --------------------------
    // 所有标签的父对象都是cont，放在【第1列】（右侧400px），按行分布
    lv_obj_t * title_label = lv_label_create(cont); // 父对象改为cont！
    lv_label_set_text(title_label, "2048 游戏");
    lv_obj_set_style_text_font(title_label, &SourceHanSansCN_Bold_20, 0);
    lv_obj_set_style_text_color(title_label, lv_color_hex(0x776e65), 0); // 深色文字更清晰
    // 放在cont的【第1列】（右）、第0行（上），横跨1列，占1行，居中对齐
    lv_obj_set_grid_cell(title_label, LV_GRID_ALIGN_CENTER, 1, 1, // 列：第1列（右），占1列，水平居中
                         LV_GRID_ALIGN_CENTER, 0, 1);             // 行：第0行（上），占1行，垂直居中

    // 分数标签
    lv_obj_t * score_label = lv_label_create(cont);
    g_score_label          = score_label; // 保存全局引用
    update_score_display(g_current_score);
    lv_label_set_text(score_label, "分数: 0");
    lv_obj_set_style_text_font(score_label, &SourceHanSansCN_Bold_20, 0);
    lv_obj_set_style_text_color(score_label, lv_color_hex(0xffffff), 0);
    lv_obj_set_style_bg_color(score_label, lv_color_hex(0x776e65), LV_PART_MAIN); // 加背景色突出分数
    lv_obj_set_style_pad_all(score_label, 10, LV_PART_MAIN);                      // 内边距避免文字贴边
    // 放在cont的【第1列】（右）、第1行（中），占1列1行，左对齐
    lv_obj_set_grid_cell(score_label, LV_GRID_ALIGN_START, 1, 1, // 水平左对齐
                         LV_GRID_ALIGN_CENTER, 1, 1);            // 垂直居中

    // 最高分标签
    highscore_label = lv_label_create(cont); // 父对象改为cont！
    lv_label_set_text(highscore_label, "最高分: 0");
    lv_obj_set_style_text_font(highscore_label, &SourceHanSansCN_Bold_20, 0);
    lv_obj_set_style_text_color(highscore_label, lv_color_hex(0xffffff), 0);
    lv_obj_set_style_bg_color(highscore_label, lv_color_hex(0x776e65), LV_PART_MAIN);
    lv_obj_set_style_pad_all(highscore_label, 10, LV_PART_MAIN);
    // 放在cont的【第1列】（右）、第1行（中），但在分数标签下方（用y轴偏移调整）
    lv_obj_set_grid_cell(highscore_label, LV_GRID_ALIGN_START, 1, 1, // 水平左对齐
                         LV_GRID_ALIGN_START, 1, 1);                 // 垂直靠上
    lv_obj_align(highscore_label, LV_ALIGN_BOTTOM_MID, 0, -20);      // 相对于分数标签向下偏移20px

    // -------------------------- 3. 底部：按钮区域（保持不变） --------------------------
    lv_obj_t * obj = lv_obj_create(cont);
    m_p->obj       = obj;
    // lv_obj_align_to(obj, cont, LV_ALIGN_BOTTOM_MID, 0, -100);
    lv_obj_add_flag(obj, LV_OBJ_FLAG_HIDDEN); // 隐藏OBJ
    lv_obj_set_style_grid_cell_y_align(obj, LV_GRID_ALIGN_END, 0);
    lv_obj_set_style_pad_all(obj, 0, LV_PART_MAIN);
    // 按钮区域横跨cont的2列（左右都占），放在第2行（底部60px）
    lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, 0, 2, LV_GRID_ALIGN_STRETCH, 2, 1);
    lv_obj_set_style_bg_color(obj, lv_color_hex(0xFFFFFF), LV_PART_MAIN);
    lv_obj_set_style_bg_opa(obj, LV_OPA_30, LV_PART_MAIN);

    lv_obj_t * btn_home = lv_btn_create(obj);
    lv_obj_center(btn_home);
    lv_obj_t * home = lv_label_create(btn_home);
    lv_label_set_text(home, LV_SYMBOL_HOME);
    m_p->head = head;
    lv_obj_add_event_cb(btn_home, home_game, LV_EVENT_CLICKED, m_p);

    lv_obj_t * btn_close = lv_btn_create(obj);
    lv_obj_align(btn_close, LV_ALIGN_RIGHT_MID, -100, 0);
    lv_obj_t * close = lv_label_create(btn_close);
    lv_label_set_text(close, LV_SYMBOL_POWER);

    lv_obj_t * btn_return = lv_btn_create(obj);
    lv_obj_align(btn_return, LV_ALIGN_LEFT_MID, 100, 0);
    lv_obj_t * label_return = lv_label_create(btn_return);
    lv_label_set_text(label_return, LV_SYMBOL_LEFT);
    m_p->g_cont_game   = g_cont_game;
    m_p->g_score_label = g_score_label;
    // m_p->g_game_timer    = g_game_timer;
    m_p->g_game_state    = &g_game_state;
    m_p->g_current_score = &g_current_score;
    lv_obj_add_event_cb(btn_return, home_game, LV_EVENT_CLICKED, m_p);

    lv_obj_t * btn_anew = lv_btn_create(temp->screen);
    lv_obj_align(btn_anew, LV_ALIGN_TOP_RIGHT, -80, 20);
    lv_obj_t * label_anew = lv_label_create(btn_anew);
    lv_label_set_text(label_anew, LV_SYMBOL_REFRESH);
    lv_obj_add_event_cb(btn_anew, reset_game, LV_EVENT_CLICKED, m_p);

    lv_obj_t * btn_re = lv_btn_create(temp->screen);
    lv_obj_align(btn_re, LV_ALIGN_TOP_RIGHT, -20, 20);
    lv_obj_t * label_menu = lv_label_create(btn_re);
    lv_label_set_text(label_menu, LV_SYMBOL_LIST);
    lv_obj_add_event_cb(btn_re, menu_game, LV_EVENT_CLICKED, m_p);

    // 显示游戏结束提示（但不覆盖棋盘）
    lv_obj_t * game_over_label = lv_label_create(temp->screen);
    m_p->game_over_label       = game_over_label;
    lv_label_set_text(game_over_label, "游戏结束！点击刷新重新开始");
    lv_obj_add_flag(game_over_label, LV_OBJ_FLAG_HIDDEN); // 隐藏OBJ
    lv_obj_align(game_over_label, LV_ALIGN_CENTER, 0, 0); // 显示在棋盘中间
    lv_obj_set_style_text_font(game_over_label, &SourceHanSansCN_Bold_20, 0);
    lv_obj_set_style_text_color(game_over_label, lv_color_hex(0xFF0000), 0);
    lv_obj_set_style_bg_color(game_over_label, lv_color_hex(0xFFFFFF), 0);
    lv_obj_set_style_bg_opa(game_over_label, LV_OPA_70, 0);
    lv_obj_set_style_pad_all(game_over_label, 10, 0);

    // 初始渲染UI
    refresh_game_ui(cont_game, data);
    slide(cont);
    // 创建游戏更新定时器（每100ms检查一次）
    game_timer_2048 = lv_timer_create(update_game_board, 100, game_over_label);
    lv_timer_set_repeat_count(game_timer_2048, -1); // 无限重复
}
